﻿using System;
using System.Diagnostics;
using System.Management;
using System.Linq;
using System.Collections.Generic;

namespace Xc.DataAccess.Processes.Extensions
{
    public static class ProcessExtensions
    {
        /// <summary>
        /// 获取该进程的命令参数
        /// </summary>
        /// <param name="process"></param>
        /// <returns></returns>
        public static string GetCommandArgs(this Process process)
        {
            try
            {
                return GetCommandLine(process.Id);
            }
            catch (Exception err)
            {
                return string.Empty;
            }
        }
        public static string[] GetCommandArgs(this Process process, char spliter)
        {
            var cmds = process.GetCommandArgs();
            if (!string.IsNullOrEmpty(cmds))
            {
                var counts = cmds.Split(spliter);
                return counts;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 获取命令行
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private static string GetCommandLine(int id)
        {
#pragma warning disable CA1416 // 验证平台兼容性
            using (var searcher = new ManagementObjectSearcher("Select CommandLine from win32_process where processid=" + id))
            {
                using (var objects = searcher.Get())
                {
                    var device = objects.Cast<ManagementBaseObject>().SingleOrDefault();
                    return device?["CommandLine"]?.ToString() ?? string.Empty;
                }
            }
#pragma warning restore CA1416 // 验证平台兼容性
        }
    }
}
